package com.itheima.dubbo.mongodb.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.commons.pojo.mongo.TimeLine;
import com.itheima.commons.pojo.mongo.Users;
import com.itheima.dubbo.interfaces.TimeLineApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;

import java.util.List;

/**
 * @author yaohu
 * @date 2021/12/7
 * @Version 1.0
 * @describe
 */
@Service
public class TimeLineApiImpl implements TimeLineApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void saveFriendTimeLine(Long userId, ObjectId id) {

        // 1.根据userId查询自己的好友表 获取好友id集合
        List<Users> usersList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), Users.class);
        List<Long> friendIds = CollUtil.getFieldValues(usersList, "friendId", Long.class);

        // 2.根据好友的id 在他们的时间线表中分别保存圈子信息
        TimeLine timeLine = new TimeLine();
        timeLine.setId(new ObjectId());
        timeLine.setUserId(userId);
        timeLine.setPublishId(id);
        timeLine.setDate(System.currentTimeMillis());

        for (Long friendId : friendIds) {
            mongoTemplate.save(timeLine, "quanzi_time_line_" + friendId);
        }
    }
}
